package com.wjb.xietong.ota.tab1;

import java.util.ArrayList;
import java.util.Calendar;
import java.util.List;

import android.content.Context;
import android.os.Bundle;
import android.os.Handler;
import android.os.Looper;
import android.os.Message;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.Button;
import android.widget.GridView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.RadioButton;
import android.widget.RadioGroup;
import android.widget.RadioGroup.OnCheckedChangeListener;
import android.widget.TextView;
import android.widget.Toast;
import com.wjb.xietong.R;
import com.wjb.xietong.control.AsyncImageLoader;
import com.wjb.xietong.control.WJBControl;
import com.wjb.xietong.datamanager.LoginUserDataManager;
import com.wjb.xietong.datamanager.WJBDataManager;
import com.wjb.xietong.ota.BaseOTA;
import com.wjb.xietong.server.IRequestResultListener;
import com.wjb.xietong.server.topic.GetCommentListParam;
import com.wjb.xietong.server.topic.GetCommentListResponse;
import com.wjb.xietong.server.topic.ReplyParam;
import com.wjb.xietong.server.topic.GetCommentListResponse.CommentInfo;
import com.wjb.xietong.server.topic.GetZanPeopleListParam;
import com.wjb.xietong.server.topic.GetZanPeopleListResponse;
import com.wjb.xietong.server.topic.GetZanPeopleListResponse.ZanPeopleInfo;
import com.wjb.xietong.util.EnumDefine.Login_User_Info;
import com.wjb.xietong.view.CVCirclePictureView;
import com.wjb.xietong.view.PullToRefreshView;
import com.wjb.xietong.view.PullToRefreshView.OnFooterRefreshListener;
import com.wjb.xietong.view.PullToRefreshView.OnHeaderRefreshListener;

public class OTAWorkMessageDetail extends BaseOTA implements
		OnHeaderRefreshListener, OnFooterRefreshListener {
	private final int MESSAGE_COMMENT_LIST_GET_DATA = 1;
	private final int MESSAGE_PRAISE_GRID_GET_DATA = 2;

	private RadioGroup top_radioGroup;
	private int current_index = 0;

	private GridView praiseGridView;
	private GridAdapter praiseGridAdapter;

	private ListView commentListView;
	private ListAdapter commentListAdapter;

	private Button btn_comment;
	private Button btn_praise;

	private List<CommentInfo> commentList = new ArrayList<CommentInfo>();
	private List<ZanPeopleInfo> praiseList = new ArrayList<ZanPeopleInfo>();

	private PullToRefreshView mPullToRefreshView;
	private final int PAGE_INDEX = 1;
	private final int NUM_EVERY_PAGE = 10;
	private int mPageIndex = 1;

	private long topicId;
	private int topicPraiseFlag;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		mPageIndex = 1;
		topicId = getIntent().getLongExtra("topic_id", 0);
		topicPraiseFlag = getIntent().getIntExtra("topic_praiseFlag", 0);

		setContentField(getLayoutInflater().inflate(
				R.layout.page_work_message_detail, null));

		setTopBarAndAction(getResources().getString(R.string.STR_PROJECT_01),
				new OnClickListener() {

					@Override
					public void onClick(View v) {
						app_.getActManager().popActivity();
					}
				}, null);

	}

	@Override
	protected void findView(View v) {
		super.findView(v);
		mPullToRefreshView = (PullToRefreshView) v
				.findViewById(R.id.main_pull_refresh_view);
		mPullToRefreshView.setOnHeaderRefreshListener(this, PAGE_INDEX);
		mPullToRefreshView.setOnFooterRefreshListener(this);

		commentListView = (ListView) v.findViewById(R.id.id_listview);
		commentListAdapter = new ListAdapter(OTAWorkMessageDetail.this);
		commentListView.setAdapter(commentListAdapter);

		praiseGridView = (GridView) v.findViewById(R.id.id_gridview);
		praiseGridAdapter = new GridAdapter(OTAWorkMessageDetail.this);
		praiseGridView.setAdapter(praiseGridAdapter);

		top_radioGroup = (RadioGroup) v.findViewById(R.id.home_radiogroup);

		top_radioGroup
				.setOnCheckedChangeListener(new OnCheckedChangeListener() {

					@Override
					public void onCheckedChanged(RadioGroup group, int checkedId) {
						switch (checkedId) {
						case R.id.radio1:
							current_index = 0;
							mPullToRefreshView.setVisibility(View.VISIBLE);
							praiseGridView.setVisibility(View.GONE);
							requestCommentData(true, mPageIndex, NUM_EVERY_PAGE);
							break;
						case R.id.radio2:
							current_index = 1;
							mPullToRefreshView.setVisibility(View.GONE);
							praiseGridView.setVisibility(View.VISIBLE);
							requestPraiseData(true, mPageIndex, NUM_EVERY_PAGE);
							break;
						}
					}
				});

		((RadioButton) top_radioGroup.getChildAt(0)).toggle();

		btn_comment = (Button) v.findViewById(R.id.id_comment);
		btn_praise = (Button) v.findViewById(R.id.id_praise);

		setBtnPraise(this.topicPraiseFlag);
	}
	
	private void setBtnPraise(int praiseFlag){
		if (praiseFlag == 1) {// 已赞
			btn_praise.setCompoundDrawablesWithIntrinsicBounds(getResources()
					.getDrawable(R.drawable.ico_praise_b), null, null, null);
			btn_praise.setText(getString(R.string.STR_WORK_CIRCLE_05));
			btn_praise.setTextColor(getResources().getColor(
					R.color.wc_has_praise));
		} else {// 未赞
			btn_praise.setCompoundDrawablesWithIntrinsicBounds(getResources()
					.getDrawable(R.drawable.ico_praise_a), null, null, null);
			btn_praise.setText(getString(R.string.STR_WORK_CIRCLE_02));
			btn_praise.setTextColor(getResources().getColor(
					R.color.wc_no_praise));
		}

	}

	@Override
	protected void setOnClickEvent() {
		super.setOnClickEvent();
		btn_comment.setOnClickListener(onclick);
		btn_praise.setOnClickListener(onclick);
	}

	OnClickListener onclick = new OnClickListener() {

		@Override
		public void onClick(View view) {
			switch (view.getId()) {
			case R.id.id_comment:
				app_.getActManager().forwardActivity(OTAWorkMessageDetail.this,
						OTAComment.class, "action_comment", topicId);
				break;
			case R.id.id_praise:
				requestPraiseById();
				break;
			default:
				break;
			}
		}
	};

	private void requestPraiseById() {
		long uniqueID = Calendar.getInstance().getTimeInMillis();
		IRequestResultListener listener = new IRequestResultListener() {

			@Override
			public void requestSuccess(long requestUniqueID) {
				topicPraiseFlag = topicPraiseFlag ==0 ? 1 :0;
				setBtnPraise(topicPraiseFlag);
			}

			@Override
			public void requestFaield(long requestUniqueID, String errCode,
					String errMsg) {
				Toast.makeText(OTAWorkMessageDetail.this,
						errMsg == null ? "网络异常..." : errMsg, Toast.LENGTH_LONG)
						.show();
			}
		};
		// 获取已赞联系人列表
		ReplyParam param4 = new ReplyParam();
		param4.setCompanyId((Long) LoginUserDataManager
				.getLoginUserInfo(Login_User_Info.COM_ID));
		// 如果当前已赞，则取消赞。 反之，则点赞
		param4.setZanType(this.topicPraiseFlag == 0 ? 1 : 0);// (0:取消赞 1:点赞)
		param4.setTopicId(this.topicId);
		param4.setUserId((Long) LoginUserDataManager
				.getLoginUserInfo(Login_User_Info.ID));
		WJBControl.requestReply(uniqueID, param4, listener);
	}

	Handler handler = new Handler(Looper.getMainLooper()) {

		@Override
		public void handleMessage(Message msg) {
			switch (msg.what) {
			case MESSAGE_COMMENT_LIST_GET_DATA:
				commentListAdapter.notifyDataSetChanged();
				break;
			case MESSAGE_PRAISE_GRID_GET_DATA:
				praiseGridAdapter.notifyDataSetChanged();
				break;
			}
			super.handleMessage(msg);
		}

	};

	private void requestCommentData(final boolean isRefresh, final int pageIndex, final int endRow) {
		long uniqueID = Calendar.getInstance().getTimeInMillis();
		IRequestResultListener listener = new IRequestResultListener() {

			@Override
			public void requestSuccess(long requestUniqueID) {
				if(isRefresh){
					commentList.clear();
				}
				setCommentListData();
			}

			@Override
			public void requestFaield(long requestUniqueID, String errCode,
					String errMsg) {
			}
		};
		GetCommentListParam param8 = new GetCommentListParam();
		param8.setCompanyId((Long) LoginUserDataManager
				.getLoginUserInfo(Login_User_Info.COM_ID));
		param8.setPageNo(pageIndex);
		param8.setPageSize(endRow);
		param8.setTopicId(topicId);
		param8.setUserId((Long) LoginUserDataManager
				.getLoginUserInfo(Login_User_Info.ID));
		WJBControl.requestGetCommentList(uniqueID, param8, listener);
	}

	private void setCommentListData() {
		GetCommentListResponse response = WJBDataManager
				.getCommentResponseInfo();
		List<CommentInfo> tempList = response.getCommentInfoList();
		if(null != tempList){
			commentList.addAll(tempList);
		}
		handler.sendEmptyMessage(MESSAGE_COMMENT_LIST_GET_DATA);
	}

	/**
	 * 暂时未做刷新和分页
	 */
	private void requestPraiseData(final boolean isRefresh, final int pageIndex, final int endRow) {
		long uniqueID = Calendar.getInstance().getTimeInMillis();
		IRequestResultListener listener = new IRequestResultListener() {

			@Override
			public void requestSuccess(long requestUniqueID) {
				setPraiseGridData();
			}

			@Override
			public void requestFaield(long requestUniqueID, String errCode,
					String errMsg) {
			}
		};
		GetZanPeopleListParam param8 = new GetZanPeopleListParam();
		param8.setCompanyId((Long) LoginUserDataManager
				.getLoginUserInfo(Login_User_Info.COM_ID));
		param8.setTopicId(topicId);
		param8.setPageNo(pageIndex);
		param8.setPageSize(100);
		param8.setUserId((Long) LoginUserDataManager
				.getLoginUserInfo(Login_User_Info.ID));
		WJBControl.requestGetZanPeopleList(uniqueID, param8, listener);
	}

	private void setPraiseGridData() {
		GetZanPeopleListResponse response = WJBDataManager
				.getZanPeopleResponseInfo();
		List<ZanPeopleInfo> tempList = response.getZanPeopleInfoList();
		praiseList.clear();
		for (int i = 0; i < tempList.size(); i++) {
			praiseList.add(tempList.get(i));
		}
		handler.sendEmptyMessage(MESSAGE_PRAISE_GRID_GET_DATA);
	}

	public class ListAdapter extends BaseAdapter {
		private LayoutInflater mInflater;

		public ListAdapter(Context context) {
			this.mInflater = LayoutInflater.from(context);
		}

		@Override
		public int getCount() {
			if (commentList == null) {
				return 0;
			} else {
				return commentList.size();
			}
		}

		@Override
		public Object getItem(int arg0) {
			return arg0;// commentList.get(arg0);
		}

		@Override
		public long getItemId(int arg0) {
			return arg0;
		}

		@Override
		public View getView(int position, View convertView, ViewGroup parent) {
			ViewHolder holder;
			if (convertView == null) {
				convertView = mInflater.inflate(
						R.layout.item_task_comment_list, null);
				holder = new ViewHolder();
				/* 得到各个控件的对象 */
				holder.icon = (CVCirclePictureView) convertView
						.findViewById(R.id.head_view);
				holder.name = (TextView) convertView.findViewById(R.id.name);
				holder.date = (TextView) convertView.findViewById(R.id.date);
				holder.llDetail = (LinearLayout) convertView
						.findViewById(R.id.id_item_txt_img_vector);

				convertView.setTag(holder); // 绑定ViewHolder对象
			} else {
				holder = (ViewHolder) convertView.getTag(); // 取出ViewHolder对象
			}

			if (commentList != null) {
				CommentInfo info = commentList.get(position);
				AsyncImageLoader.Instance().loadDrawableForImageView(
						info.getTopic_title(), holder.icon,
						R.drawable.taskdetail_temp_flag);
				holder.name.setText(info.getUser_nick());
				holder.date.setText(info.getGmt_modified());

				holder.llDetail.removeAllViews();
				String contentInfo = info.getContent();
				if (null != contentInfo) {
					TextView txt = new TextView(OTAWorkMessageDetail.this);
					txt.setText("" + contentInfo);
					holder.llDetail.addView(txt, new LinearLayout.LayoutParams(
							LinearLayout.LayoutParams.MATCH_PARENT,
							LinearLayout.LayoutParams.WRAP_CONTENT));
				}
			}

			return convertView;
		}

		/* 存放控件 的ViewHolder */
		public final class ViewHolder {
			public CVCirclePictureView icon;
			public TextView name;
			public TextView date;
			public LinearLayout llDetail;
		}
	}

	public class GridAdapter extends BaseAdapter {
		private LayoutInflater mInflater;

		public GridAdapter(Context context) {
			this.mInflater = LayoutInflater.from(context);
		}

		@Override
		public int getCount() {
			if (praiseList == null) {
				return 0;
			} else {
				return praiseList.size();
			}
		}

		@Override
		public Object getItem(int arg0) {
			return arg0;// commentList.get(arg0);
		}

		@Override
		public long getItemId(int arg0) {
			return arg0;
		}

		@Override
		public View getView(int position, View convertView, ViewGroup parent) {
			ViewHolder holder;
			if (convertView == null) {
				convertView = mInflater.inflate(
						R.layout.item_comment_praise_gridview, null);
				holder = new ViewHolder();
				/* 得到各个控件的对象 */
				holder.icon = (CVCirclePictureView) convertView
						.findViewById(R.id.head_view);
				holder.name = (TextView) convertView.findViewById(R.id.name);

				convertView.setTag(holder); // 绑定ViewHolder对象
			} else {
				holder = (ViewHolder) convertView.getTag(); // 取出ViewHolder对象
			}

			if (praiseList != null) {
				ZanPeopleInfo info = praiseList.get(position);
				AsyncImageLoader.Instance().loadDrawableForImageView(
						info.getUserFlag(), holder.icon,
						R.drawable.taskdetail_temp_flag);
				holder.name.setText(info.getUserName());
			}

			return convertView;
		}

		/* 存放控件 的ViewHolder */
		public final class ViewHolder {
			public CVCirclePictureView icon;
			public TextView name;
		}
	}

	@Override
	public void onFooterRefresh(PullToRefreshView view, final int pageIndex) {
		mPullToRefreshView.postDelayed(new Runnable() {
			@Override
			public void run() {
				mPullToRefreshView.onFooterRefreshComplete();
				mPageIndex = pageIndex;
				System.out.println("onFooterRefresh pageIndex:" + pageIndex);
				requestCommentData(false, pageIndex, NUM_EVERY_PAGE);
			}
		}, 1000);
	}

	@Override
	public void onHeaderRefresh(PullToRefreshView view, final int pageIndex) {
		mPullToRefreshView.postDelayed(new Runnable() {

			@Override
			public void run() {
				mPullToRefreshView.onHeaderRefreshComplete();
				mPageIndex = pageIndex;
				System.out.println("onHeaderRefresh pageIndex:" + pageIndex);
				requestCommentData(true, pageIndex, NUM_EVERY_PAGE);
			}
		}, 1000);
	}
}
